package top.xiesen.collection;

/**
 * 自己写LinkedList,理解LinkedList的底层结构
 * 
 * @author Allen
 *
 */
public class MyLinkedList {

	private Node first;
	private Node last;

	private int size;

	public void add(Object obj) {
		if (first == null) {
			Node n = new Node();
			n.setPrevious(null);
			n.setObj(obj);
			n.setNext(null);
			first = n;
			last = n;
		} else {
			Node n = new Node();
			n.setPrevious(last);
			n.setObj(obj);
			n.setPrevious(null);

			last.setNext(n);
			last = n;
		}
		size++;
	}

	public int size() {
		return size;
	}

	// 越界处理
	private void rangeCheck(int index) {
		if (index < 0 || index > size) {
			try {
				throw new Exception();
			} catch (Exception e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}
	}

	// 获取对应节点的值
	public Object get(int index) {
		// index 越界
		rangeCheck(index);
		Node temp = node(index);
		if (temp != null) {
			return temp.obj;
		}
		return null;
	}

	// 获取节点
	public Node node(int index) {
		Node temp = null;
		if (first != null) {
			temp = first;
			for (int i = 0; i < index; i++) {
				temp = temp.next;
			}
		}
		return temp;
	}

	// 移除对应节点的值
	public void remove(int index) {
		// 获取节点
		Node temp = node(index);
		
		if (temp != null) {
			Node up = temp.previous;
			Node down = temp.next;
			up.next = down;
			down.previous = up;
			size--;
		}
	}

	
	public void add(int index,Object obj){
		// 获取节点
		Node temp = node(index);
		Node newNode = new Node();
		newNode.obj = obj;
		
		if(temp != null){
			Node up = temp.previous;
			up.next = newNode;
			newNode.previous = up;
			newNode.next = temp;
			temp.previous = newNode;
			size++;
		}
		
	}
	public static void main(String[] args) {
		MyLinkedList list = new MyLinkedList();
		list.add("aaa");
		list.add("bbb");
//		list.add(1,"BBB");
		list.add("ccc");
		list.add("ddd");
//		list.remove(1);

		System.out.println(list.get(1));
		System.out.println(list.size);

	}
}
